package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowData;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowProperties;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowResponse;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.BindFamilyMemberDto;
import com.zzyl.nursing.dto.DeviceDataDayVo;
import com.zzyl.nursing.dto.DeviceDataQueryDto;
import com.zzyl.nursing.dto.LoginUserDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.DeviceDataHourlyVo;
import com.zzyl.nursing.vo.FamilyBindElderVo;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import com.zzyl.nursing.vo.LoginUserVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 老人家属Service业务层处理
 *
 * @author mr.wu
 * @date 2025-05-23
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    /**
     * 用户昵称名前缀集合
     */
    private static List<String> NICK_NAME_PREFIX_LIST = Arrays.asList("钱途无量",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IElderService elderService;

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public LoginUserVo login(LoginUserDto dto) {
        //1. 调用微信小程序登录接口获取openId
        String openId = wechatService.getOpenId(dto.getCode());
        if(StringUtils.isBlank(openId)) {
            throw new BaseException("获取openId失败");
        }

        //2. 根据openId查询用户数据
        FamilyMember member = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();

        //3. 如果用户不存在，则新增用户（自动注册）
        if(member==null) {
            Collections.shuffle(NICK_NAME_PREFIX_LIST);

            //随机生成昵称
            String nickName = NICK_NAME_PREFIX_LIST.get(0) + RandomStringUtils.randomNumeric(4);

            member = FamilyMember.builder().name(nickName).openId(openId).build();
            boolean result = this.save(member);
            if(!result) {
                throw new BaseException("新增用户失败");
            }
        }

        //4. 判断用户手机号如果不存在，则调用微信获取手机号接口得到手机号
        if(StringUtils.isBlank(member.getPhone())) {
            String phone = wechatService.getPhone(dto.getPhoneCode());
            if(StringUtils.isBlank(phone)){
                throw new BaseException("获取手机号失败");
            }

            //5. 得到手机号后则完成用户表的更新
            boolean result = this.lambdaUpdate().eq(FamilyMember::getId, member.getId())
                    .set(FamilyMember::getPhone, phone).update();
            if(!result) {
                throw new BaseException("更新手机号失败");
            }
        }

        //6. 生成登录成功用户的令牌（Token）
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("userId", member.getId());//设置用户
        userMap.put("name",member.getName());//用户昵称
        String token = tokenService.createToken(userMap);//生成令牌

        //7. 构建响应数据
        return LoginUserVo.builder().nickName(member.getName()).token(token).build();
    }

    /**
     * 绑定家人
     *
     * @param dto 绑定家人请求参数
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int bindFamilyMember(BindFamilyMemberDto dto) {
        // 参数校验
        if (StringUtils.isBlank(dto.getIdCard()) || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getRemark())) {
            throw new BaseException("参数不能为空");
        }

        // 获取当前登录用户ID
        Long userId = UserThreadLocal.getUserId();
        if (userId == null) {
            throw new BaseException("用户未登录");
        }

        // 验证老人是否存在,并获得老人id
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getIdCard())
                .eq(Elder::getName, dto.getName())
                .one();
        if (elder == null) {
            throw new BaseException("该老人不存在或未入住养老院");
        }
        // 获得老人ID
        Long elderId = elder.getId();

        // 查询表family_bind_elder,检查是否已经绑定
        List<FamilyBindElder> existBinding = familyMemberMapper.selectbind(elderId, userId);
        if (existBinding != null && !existBinding.isEmpty()) {
            throw new BaseException("该老人已绑定");
        }

        // 创建绑定关系
        FamilyBindElder familyBindElder = new FamilyBindElder();
        familyBindElder.setCreateBy(userId);
        familyBindElder.setCreateTime(LocalDateTime.now());
        familyBindElder.setElderId(elderId);
        familyBindElder.setFamilyMemberId(userId);
        familyBindElder.setRemark(dto.getRemark());
        familyBindElder.setUpdateBy(userId);
        familyBindElder.setUpdateTime(LocalDateTime.now());

        // 保存绑定关系
        boolean result = familyMemberMapper.insertFamilyBindElder(familyBindElder);
        if (!result) {
            throw new BaseException("绑定家人失败");
        }
        return 1;
    }

    /**
     * 查询家人列表
     * @return
     */
    @Override
    public List<FamilyBindElderVo> selectMyFamilyList() {
        // 获取当前登录用户ID
        Long userId = UserThreadLocal.getUserId();
        if (userId == null) {
            throw new BaseException("用户未登录");
        }

        // 查询家人列表
        return familyMemberMapper.selectMyFamilyList(userId);
    }

    /**
     * 分页查询家属老人信息
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<FamilyMemberElderVo> selectFamilyMemberElderPage(Integer pageNum, Integer pageSize, Long userId) {
        Page<FamilyMemberElderVo> page = new Page<>(pageNum, pageSize);
        return familyMemberMapper.selectFamilyMemberElderPage(page, userId);
    }


    /**
     * 按天统计查询指标数据
     * @param queryDto
     * @return
     */
    @Autowired
    private IDeviceDataService deviceDataService;
    @Override
    public List<DeviceDataHourlyVo> queryDeviceDataListByDay(DeviceDataQueryDto queryDto) {

        Long time= (long) (1000*60*60);    // 一个小时的毫秒数

        List<DeviceDataHourlyVo> deviceDataDayVoList=new ArrayList<>();  // 存放每个小时的数据
        for (int i = 0; i < 24; i++) {
            // 使用 Instant 将毫秒值转换为时间点
            Instant instant1 = Instant.ofEpochMilli(queryDto.getStartTime()+i*time);   //  创建时间点
            // 转换为 LocalDateTime，使用系统默认时区
            LocalDateTime startDateTime1 = LocalDateTime.ofInstant(instant1,ZoneId.of("Asia/Shanghai"));  //  创建时间点

            Instant instant2 = Instant.ofEpochMilli(queryDto.getStartTime()+(i+1)*time);
            // 转换为 LocalDateTime，使用系统默认时区
            LocalDateTime startDateTime2 = LocalDateTime.ofInstant(instant2, ZoneId.systemDefault());

            List<DeviceData> deviceDataList = deviceDataService.lambdaQuery()
                    .eq(DeviceData::getIotId, queryDto.getIotId())
                    .eq(DeviceData::getFunctionId,queryDto.getFunctionId())
                    .gt(DeviceData::getAlarmTime,startDateTime1)
                    .lt(DeviceData::getAlarmTime,startDateTime2)
                    .list();  // 查询指定时间段的数据
            //设备数据为空
            if (CollUtil.isEmpty(deviceDataList)){
                String dateTime = startDateTime1.toLocalTime().toString();
                deviceDataDayVoList.add(new DeviceDataHourlyVo(dateTime,0.0));
                continue;
            }
            List<Double> dataValueList = deviceDataList.stream().map(x -> {
                String dataValue = x.getDataValue();
                return Double.valueOf(dataValue);
            }).collect(Collectors.toList());
            OptionalDouble average = dataValueList.stream().mapToInt(Double::intValue)
                    .average();  // 求平均值
            String dateTime = startDateTime1.format(DateTimeFormatter.ofPattern("HH:mm"));
            Double dataValue=  average.getAsDouble();    //  平均值转化为double类型
            DeviceDataHourlyVo deviceDataDayVo = new DeviceDataHourlyVo(dateTime, dataValue);
            deviceDataDayVoList.add(deviceDataDayVo);
        }
        return deviceDataDayVoList;


        // // 参数校验
        // if (queryDto.getStartTime() == null || queryDto.getEndTime() == null
        //         || queryDto.getFunctionId() == null || queryDto.getIotId() == null) {
        //     throw new BaseException("参数不能为空");
        // }
        //
        // // 查询数据库获取每小时的平均值
        // List<DeviceDataHourlyVo> result = familyMemberMapper.queryDeviceDataListByDay(
        //         queryDto.getIotId(),
        //         queryDto.getFunctionId(),
        //         queryDto.getStartTime(),
        //         queryDto.getEndTime()
        // );
        //
        // // 如果没有数据，返回24小时的空数据
        // if (result == null || result.isEmpty()) {
        //     result = new ArrayList<>();
        //     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        //     for (int hour = 0; hour < 24; hour++) {
        //         DeviceDataHourlyVo vo = new DeviceDataHourlyVo();
        //         vo.setDateTime(String.format("%02d:00", hour));
        //         vo.setDataValue(0.0);
        //         result.add(vo);
        //     }
        // }
        //
        // return result;
    }

    @Autowired
    private IoTDAClient client;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;
    @Autowired
    private DeviceMapper deviceMapper;
    /**
     * 查询健康数据
     *
     * @param deviceName
     * @return
     */
    @Override
    public Map<String, Object> getDevicePropertyStatus(String deviceName) {
        //1. 判断设备是否存在
        Device device = deviceMapper.selectDeviceByDeviceName(deviceName);
        if(device==null) {
            throw new BaseException("设备不存在");
        }
        String deviceId = device.getIotId();//获取设备id

        //2. 调用华为云IOT接口查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(deviceId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if(response==null || response.getHttpStatusCode()!=200) {
            throw new BaseException("调用华为云IOT接口查询设备影子数据失败");
        }

        //3. 解析响应结果数据，封装map的数据
        List<DeviceShadowData> shadowDataList = response.getShadow();
        if(CollUtil.isEmpty(shadowDataList)) {
            throw new BaseException("调用华为云IOT接口查询设备影子数据为空");
        }
        DeviceShadowData shadowData = shadowDataList.get(0);
        DeviceShadowProperties reported = shadowData.getReported();


        JSONObject properties = JSONUtil.parseObj(reported.getProperties());
        //事件操作时间，格式：yyyyMMdd'T'HHmmss'Z'，如20151212T121212Z。该值是国际标准时间，比东八区早八小时
        String eventTimeStr = reported.getEventTime();//数据上报时间
        //转为时间戳
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime dateTime = LocalDateTime.parse(eventTimeStr, formatter);
        long time = dateTime.atZone(ZoneId.of("UTC")).toInstant().toEpochMilli();


        List<Map<String,Object>> propertyStatusInfo = new ArrayList<>();
        Map<String,Object> heartMap = new HashMap<>();
        properties.forEach((k,v)->{
            if ("HeartRate".equals(k)){
                //封装属性对象
                heartMap.put("dataType","int");
                heartMap.put("identifier",k);
                heartMap.put("name","心率");
                heartMap.put("value",v);
                heartMap.put("unit","");
                heartMap.put("time",time);
            } else {
                Map<String,Object> propertyMap = new HashMap<>();
                propertyMap.put("dataType","int");
                propertyMap.put("identifier",k);
                propertyMap.put("value",v);
                propertyMap.put("unit","");
                propertyMap.put("time",time);
                propertyStatusInfo.add(propertyMap);
            }
        });
        propertyStatusInfo.add(heartMap);
        //4. 返回Map数据
        Map<String,Object> resultMap = new HashMap<>();

        Map<String,Object> propertyStatusInfoMap = new HashMap<>();
        propertyStatusInfoMap.put("propertyStatusInfo", propertyStatusInfo);

        resultMap.put("list",propertyStatusInfoMap);

        return resultMap;
    }

    /**
     * 按周统计查询指标数据
     *
     * @param iotId
     * @param functionId
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public List<DeviceDataDayVo> queryDeviceDataListByWeek(String iotId, String functionId, Long startTime, Long endTime) {

        Long time= (long) (1000*60*60*24);    // 一天的毫秒数

        List<DeviceDataDayVo> deviceDataDayVoList=new ArrayList<>();  // 存放每天数据
        for (int i = 0; i < 7; i++) {
            // 使用 Instant 将毫秒值转换为时间点
            Instant instant1 = Instant.ofEpochMilli(startTime+i*time);   //  创建时间点
            // 转换为 LocalDateTime，使用系统默认时区
            LocalDateTime startDateTime1 = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault());  //  创建时间点

            Instant instant2 = Instant.ofEpochMilli(startTime+(i+1)*time);
            // 转换为 LocalDateTime，使用系统默认时区
            LocalDateTime startDateTime2 = LocalDateTime.ofInstant(instant2, ZoneId.systemDefault());

            List<DeviceData> deviceDataList = deviceDataService.lambdaQuery()
                    .eq(DeviceData::getIotId, iotId)
                    .eq(DeviceData::getFunctionId, functionId)
                    .gt(DeviceData::getAlarmTime,startDateTime1)
                    .lt(DeviceData::getAlarmTime,startDateTime2)
                    .list();  // 查询指定时间段的数据
            //设备数据为空
            if (CollUtil.isEmpty(deviceDataList)){
                String dateTime = startDateTime1.toLocalDate().toString();
                String[] split = dateTime.split("-");
                dateTime=split[1]+"."+split[2];
                deviceDataDayVoList.add(new DeviceDataDayVo(dateTime,0.0));
                continue;
            }
            List<Double> dataValueList = deviceDataList.stream().map(x -> {
                String dataValue = x.getDataValue();
                return Double.valueOf(dataValue);
            }).collect(Collectors.toList());
            OptionalDouble average = dataValueList.stream().mapToInt(Double::intValue)
                    .average();  // 求平均值
            String dateTime = startDateTime1.toLocalDate().toString();  // 2025-06 -01
            String[] split = dateTime.split("-");
            dateTime=split[1]+"."+split[2];
            Double dataValue=  average.getAsDouble();    //  平均值转化为double类型
            DeviceDataDayVo deviceDataDayVo = new DeviceDataDayVo(dateTime, dataValue);
            deviceDataDayVoList.add(deviceDataDayVo);
        }

        return deviceDataDayVoList;
    }
}
